package com.bradz.mytv;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.TimerTask;

import org.json.JSONException;
import org.json.JSONObject;

import com.android.vending.billing.IInAppBillingService;
import com.bradz.mytv.activityHelp.Constants;
import com.bradz.mytv.activityHelp.LoadBillingTask;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.IntentSender.SendIntentException;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.RemoteException;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

public class activityCurrentChannels extends ListActivity{
	private classNetworkHolder network;
	private Context self;
	private applicationGlobalVars globals;
	private ImageView verify_network;
	private LinearLayout popup_layout_newChannel, popup_layout_deleteChannel;
	private PopupWindow popUp_newChannel;
	private boolean click;
	private Display display;
	private ChannelAdapter c_adapter;
	private TextView manage_channels_options,network_status;
	private Typeface font_italic,font_bold,font_book,font_title;
	
	private IInAppBillingService mService;
	private ServiceConnection mServiceConn;
	private classAndroidLogger logger;
	Bundle buyIntentBundle;
	
	Handler myHandler = new Handler() {

  	    @Override
  	    public void handleMessage(Message msg) {
  	        switch (msg.what) {
	  	        case 0:
	  	        	sent_donation_purchase();
	  	            break;
	  	        default:
	  	            break;
  	        }
  	    }
  	};

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        self = this;
        globals = ((applicationGlobalVars) this.getApplication());
        logger = new classAndroidLogger("ActivityMain");
        bind_billing_activities();
        font_italic = Typeface.createFromAsset(getAssets(),"fonts/Neutraface2Text-BookItalic.otf");
        font_bold = Typeface.createFromAsset(getAssets(),"fonts/Neutraface2Text-Bold.otf");
		font_book = Typeface.createFromAsset(getAssets(),"fonts/Neutraface2Text-Book.otf");
		font_title = Typeface.createFromAsset(getAssets(),"fonts/Neutraface2Text-Demi.otf");
        load_network();
    }
    
    @Override
    public void onResume(){
    	super.onResume();
    	//This needs to be here so that the network is updated whenever
    	//an activity returns to this activity.
    	new initialize_network_task().execute(false);
    }
    
    public void load_network(){
    	setContentView(R.layout.activity_current_channels);
    	network_status = (TextView)findViewById(R.id.network_status);
		network_status.setTypeface(font_book);
    	new initialize_network_task().execute(false);
    }
    
    public void set_things_up(){
        //ArrayAdapter<String> adapter = new ArrayAdapter<String>(self,R.layout.file_row, network.get_channel_names());
        //setListAdapter(adapter); 
        
    	List<String> channels = Arrays.asList(network.get_channel_names());
    	//Collections.sort(channels);
        c_adapter = new ChannelAdapter(self, R.layout.file_row2, channels);
        setListAdapter(c_adapter);
        
    	TextView manage_channels_title = (TextView)findViewById(R.id.manage_channels_title);
        manage_channels_options = (TextView)findViewById(R.id.manage_channels_options);
        manage_channels_title.setTypeface(font_title);
		TextView network_status = (TextView)findViewById(R.id.network_status);
		network_status.setTypeface(font_book);
        manage_channels_options.setTypeface(font_italic);
        
        create_add_channel_popup();
        
        display = getWindowManager().getDefaultDisplay();
        final classInfoPopUp info_popup = new classInfoPopUp(self,this.getBaseContext(),getAssets(),myHandler);
		//Sends in the image and the display so that the actions can be attached and the popup can be placed correctly
		info_popup.attach_popup_window((ImageView)findViewById(R.id.info_button),display);
        
        initialize_buttons();
    }
    
    public void create_add_channel_popup(){
        popUp_newChannel = new PopupWindow(self);
        popup_layout_newChannel = new LinearLayout(this);
        popup_layout_newChannel.setBackgroundColor(Color.WHITE);
        popup_layout_newChannel.setOrientation(1);
        popup_layout_newChannel.setGravity(Gravity.CENTER);
        
        LinearLayout popup_layout_0 = new LinearLayout(this);
        popup_layout_0.setGravity(Gravity.RIGHT);
        popup_layout_0.setPadding(0, 0, 20, 50);
	        TextView popUp_X = new TextView(this);
	        popUp_X.setTextSize(24);
	        popUp_X.setTextColor( getResources().getColor(R.color.popup_text));
	        popUp_X.setText("X");
	        popUp_X.setTypeface(font_bold);
	        popUp_X.setOnClickListener(new View.OnClickListener() {
	            public void onClick(View v) {
	            	popUp_newChannel.dismiss();
	            }
	        });
	    popup_layout_0.addView(popUp_X);
        
        LinearLayout popup_layout_1 = new LinearLayout(this);
        popup_layout_1.setGravity(Gravity.CENTER);
        popup_layout_1.setPadding(40, 0, 40, 20);
	        TextView popUp_title = new TextView(this);
	        popUp_title.setTextSize(24);
	        popUp_title.setTextColor( getResources().getColor(R.color.popup_text));
	        popUp_title.setText("New Channel Name:");
	        popUp_title.setTypeface(font_italic);
        popup_layout_1.addView(popUp_title);
        
        LinearLayout popup_layout_2 = new LinearLayout(this);
        popup_layout_2.setGravity(Gravity.CENTER);
        popup_layout_2.setPadding(20, 0, 20, 0);
        	final EditText popUp_edit_text = new EditText(this);
        	//final TextView popUp_edit_text = new TextView(this);
	        popUp_edit_text.setEms(20);
	        popUp_edit_text.setClickable(true);
	        popUp_edit_text.setEnabled(true);
	        popUp_edit_text.setFocusableInTouchMode(true);
	        popUp_edit_text.setFocusable(true);
	    popup_layout_2.setFocusable(true);
	    popup_layout_2.setFocusableInTouchMode(true);
	    popup_layout_2.addView(popUp_edit_text);
        
	    LinearLayout popup_layout_3 = new LinearLayout(this);
        popup_layout_3.setGravity(Gravity.CENTER);
        popup_layout_3.setPadding(40, 20, 40, 0);
	        Button popUp_next_button = new Button(this);
	        popUp_next_button.setBackgroundColor(getResources().getColor(R.color.popup_text));
	        popUp_next_button.setTextColor(getResources().getColor(R.color.button_color));
	        //float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, getResources().getDisplayMetrics());
	        //popUp_next_button.setWidth((int)px);
	        popUp_next_button.setText("Next");
	        popUp_next_button.setTypeface(font_book);
	        popUp_next_button.setOnClickListener(new View.OnClickListener() {
	            public void onClick(View v) {
	            	if(!popUp_edit_text.getText().toString().isEmpty()){
	            		Intent myIntent = new Intent(getBaseContext(), activityAddChannel.class);
	            		//network.add_channel_get_id(popUp_edit_text.getText().toString());
	            		//channel_database.add_channel(mEdit.getText().toString());
	            		popUp_newChannel.dismiss();
	            		myIntent.putExtra("channel_id", network.add_channel_get_id(popUp_edit_text.getText().toString()));
	            		startActivity(myIntent);
	            	}else{
	            		new AlertDialog.Builder(activityCurrentChannels.this)
	                    .setTitle("Error")
	                    .setMessage("Give your channel a name!")
	                    .show();
	            	}
	            }
	        });
	    popup_layout_3.addView(popUp_next_button);
	    
	    popup_layout_newChannel.addView(popup_layout_0);
	    popup_layout_newChannel.addView(popup_layout_1);
	    popup_layout_newChannel.addView(popup_layout_2);
	    popup_layout_newChannel.addView(popup_layout_3);
	    popup_layout_newChannel.setFocusable(true);
	    popup_layout_newChannel.setFocusableInTouchMode(true);
        click = true;
        //popup_layout
        //popUp.setContentView(findViewById(R.layout.name_channel_popup));
        popUp_newChannel.setContentView(popup_layout_newChannel);
        popUp_newChannel.setFocusable(true);
        popUp_edit_text.post(new Runnable() {
            public void run() {
            	popUp_edit_text.requestFocus();
            }
        });
    }
    
	public void initialize_buttons(){
		manage_channels_options.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("NewApi")
			public void onClick(View v) {
            	if (click){
	            	Log.i("currentChannel","add channels clicked");
	            	//The recovery table has to be reset everytime these clicks are called to avoid bad references
	            	/*network.reset_recovery_database();
	        		Intent myIntent = new Intent(getBaseContext(), activityNameChannel.class);
	        		startActivity(myIntent);*/
	            	
	            	Point size = new Point();
	            	try {
	                    display.getSize(size);
	                } catch (java.lang.NoSuchMethodError ignore) { // Older device
	                	size.x = display.getWidth();
	                	size.y = display.getHeight();
	                }
	            	popUp_newChannel.showAtLocation(popup_layout_newChannel, Gravity.CENTER, 0, 0);
	            	popUp_newChannel.update(0, 0, size.x-(size.x/4), size.y-(2*size.y/5));
	                //popUp.setFocusable(true);
	                click = false;
            	}else{
            		//popUp.setFocusable(false);
            		popUp_newChannel.dismiss();
            		click = true;
            	}
            }
        });
	}
	
	private class ChannelAdapter extends ArrayAdapter<String> {

        private List<String> items;
        private PopupWindow popUp_deleteChannel;

        public ChannelAdapter(Context context, int textViewResourceId, List<String> items) {
                super(context, textViewResourceId, items);
                this.items = items;
        }
        public void refresh_delete_channel_popup(final int position){
        	popUp_deleteChannel = new PopupWindow(self);
        	popup_layout_deleteChannel = new LinearLayout(self);
        	popup_layout_deleteChannel.setBackgroundColor(Color.WHITE);
            //Orientation = Vertical
        	popup_layout_deleteChannel.setOrientation(1);
        	popup_layout_deleteChannel.setGravity(Gravity.CENTER);
            
        	LinearLayout.LayoutParams layout_params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 
        			LinearLayout.LayoutParams.MATCH_PARENT, .5f);
        	
            LinearLayout popup_layout_0 = new LinearLayout(self);
            popup_layout_0.setGravity(Gravity.RIGHT);
            popup_layout_0.setPadding(0, 0, 20, 0);
            	TextView popUp_X = new TextView(self);
            	popUp_X.setTextSize(24);
    	        popUp_X.setTextColor(getResources().getColor(R.color.popup_text));
    	        popUp_X.setText("X");
    	        popUp_X.setTypeface(font_bold);
    	        popUp_X.setOnClickListener(new View.OnClickListener() {
    	            public void onClick(View v) {
    	            	popUp_deleteChannel.dismiss();
    	            }
    	        });
            popup_layout_0.addView(popUp_X);
            
            LinearLayout popup_layout_1 = new LinearLayout(self);
            popup_layout_1.setGravity(Gravity.CENTER);
            popup_layout_1.setPadding(40, 20, 40, 0);
    	        TextView popUp_title = new TextView(self);
    	        popUp_title.setTextSize(24);
    	        popUp_title.setTextColor(getResources().getColor(R.color.popup_text));
    	        popUp_title.setText("Are you sure you want to delete this channel?");
    	        popUp_title.setTypeface(font_italic);
    	        popUp_title.setGravity(Gravity.CENTER);
            popup_layout_1.addView(popUp_title);
            
            LinearLayout popup_layout_2 = new LinearLayout(self);
            popup_layout_2.setGravity(Gravity.CENTER);
            popup_layout_2.setPadding(60, 25, 60, 40);
            popup_layout_2.setOrientation(0);
            popup_layout_2.setLayoutParams(layout_params);
    	        Button popUp_yes_button = new Button(self);
    	        popUp_yes_button.setBackgroundColor(getResources().getColor(R.color.yes_color));
    	        popUp_yes_button.setTextColor(getResources().getColor(R.color.button_color));
    	        popUp_yes_button.setText("YES");
    	        popUp_yes_button.setTypeface(font_bold);
    	        popUp_yes_button.setOnClickListener(new View.OnClickListener() {
    	            public void onClick(View v) {
    	            	network.reset_recovery_database();
    	            	//Deletes channel in database
                    	network.delete_channel(network.get_channel_names()[position]);
                    	//deletes channel in object
                    	network.remove_channel_position(position);
                    	//saves channel
                    	globals.set_network_object(network);
        				globals.set_network_loaded(true);
                    	//new initialize_network_task().execute(true);
                    	
                    	set_things_up();
                    	popUp_deleteChannel.dismiss();
    	            }
    	        });
    	        layout_params.setMargins(0, 0, 15, 0);
    	        popUp_yes_button.setLayoutParams(layout_params);
    	        popUp_yes_button.setTextSize(24);
    	        Button popUp_no_button = new Button(self);
    	        popUp_no_button.setBackgroundColor(getResources().getColor(R.color.no_color));
    	        popUp_no_button.setTextColor(getResources().getColor(R.color.button_color));
    	        popUp_no_button.setText("NO");
    	        popUp_no_button.setTypeface(font_bold);
    	        popUp_no_button.setOnClickListener(new View.OnClickListener() {
    	            public void onClick(View v) {
    	            	popUp_deleteChannel.dismiss();
    	            }
    	        });
    	        layout_params.setMargins(15, 0, 0, 0);
    	        popUp_no_button.setLayoutParams(layout_params);
    	        popUp_no_button.setTextSize(24);
         popup_layout_2.addView(popUp_yes_button);
         popup_layout_2.addView(popUp_no_button);
         
         popup_layout_deleteChannel.addView(popup_layout_0);
         popup_layout_deleteChannel.addView(popup_layout_1);
         popup_layout_deleteChannel.addView(popup_layout_2);
         
         popup_layout_deleteChannel.setFocusable(true);
         popup_layout_deleteChannel.setFocusableInTouchMode(true);
         //popup_layout
         //popUp.setContentView(findViewById(R.layout.name_channel_popup));
         popUp_deleteChannel.setContentView(popup_layout_deleteChannel);
         popUp_deleteChannel.setFocusable(true);
        }
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
                View v = convertView;
                if (v == null) {
                    LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    v = vi.inflate(R.layout.file_row2, null);
                }
                String text = items.get(position);
                if (text != null) {
                    TextView tt = (TextView) v.findViewById(R.id.file_view);
                    tt.setTypeface(font_book);
                    TextView bt = (TextView) v.findViewById(R.id.delete_view);
                    bt.setTypeface(font_bold);
                    if (tt != null) {
                    	tt.setText(text);
                    	tt.setOnClickListener(new View.OnClickListener() {
                            public void onClick(View v) {
                            	if (verify_network.getVisibility()!=4 && !network.not_initialized && network.get_channels().size()>0){
	                            	network.set_current_channel(position);
	                            	Intent myIntent = new Intent(getBaseContext(), activityCurrentShows.class);
	    					    	myIntent.putExtra("channel_id", network.get_current_channel().get_channel_number());
	    							startActivity(myIntent);
                            	}
                            }
                        });
                    	bt.setText("X");
                    	bt.setOnClickListener(new View.OnClickListener() {
                            @SuppressLint("NewApi")
							public void onClick(View v) {
                            	//Make sure that there are channels here and it doesn't just say "No Channels"
                            	if (verify_network.getVisibility()!=4 && !network.not_initialized && network.get_channels().size()>0){
	                            	Log.i("activityCurrentChannel","X Clicked");
	                            	refresh_delete_channel_popup(position);
	                            	Point size = new Point();
	                            	try {
	                                    display.getSize(size);
	                                } catch (java.lang.NoSuchMethodError ignore) { // Older device
	                                	size.x = display.getWidth();
	                                	size.y = display.getHeight();
	                                }
	            	            	popUp_deleteChannel.showAtLocation(popup_layout_deleteChannel, Gravity.CENTER, 0, 0);
	            	            	popUp_deleteChannel.update(0, 0, size.x-(size.x/3), size.y-(2*size.y/5));
                            	}
                            }
                        });
                    }
                }
                return v;
        }
	}
	
	//This loads the global network into the current activity
	private class initialize_network_task extends AsyncTask<Boolean, Integer, Void> {

		@Override
        protected void onPreExecute() {
			String[] loading = {"Loading..."};
			verify_network = (ImageView)findViewById(R.id.network_indicator);
			verify_network.setImageDrawable(getResources().getDrawable(R.drawable.object_circle_red));
			verify_network.setVisibility(View.INVISIBLE);
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(self,R.layout.file_row, loading);
			setListAdapter(adapter);
		}
		
		@Override
		protected Void doInBackground(Boolean... update_network) {
			if(!update_network[0]){
				Log.i("activityCurrentChannel - Thread","Pulling Network...");
				//This waits for the global network to be created
				if(!globals.get_network_loaded()){
					network = new classNetworkHolder(self,true,globals.get_random());
					classChannelDatabase channel_database = network.get_channel_database();
					ArrayList<classChannelHolder> channels = new ArrayList<classChannelHolder>();
					ArrayList<Integer> channel_numbers = new ArrayList<Integer>(channel_database.get_all_channels());
					ArrayList<classRecovery> recovery_table = new ArrayList<classRecovery>(channel_database.get_recovery_table());
					classChannelHolder channel_holder;
					for(int i = 0; i < channel_numbers.size();i++){
						channel_holder = new classChannelHolder(channel_numbers.get(i), 
								channel_database.get_channel_name(channel_numbers.get(i)), 
								channel_database.get_channel_paths(channel_numbers.get(i)),true);
						//What is the point of having a channel with no episodes?
						if (channel_holder.channel_size() > 0){
							channels.add(channel_holder);
							//
							if (i<recovery_table.size()){
								channels.get(recovery_table.get(i).channel_number).get_episode(recovery_table.get(i).channel_episode);
								channels.get(recovery_table.get(i).channel_number).set_episode_offset(recovery_table.get(i).episode_offset);
							}
						}
						int progress  = (int) (((i+1) / (float) channel_numbers.size()) * 100);
						Log.i("activityLoadingScreen","Progress: " + String.valueOf(progress) + "%");
						publishProgress(progress);
					}
					network.async_network_update(channels);
				}else{
					network = globals.get_network_object();
				}
			}else{
				Log.i("activityCurrentChannel - Thread","Saving Network...");
				//Resaves the global network when the activity is resumed. This assumes that the network
				//has been changed in the config in some way. Thrown together mutex lock
				globals.set_network_loaded(false);
				if(!globals.get_network_loaded()){
					network = new classNetworkHolder(self,true,globals.get_random());
					classChannelDatabase channel_database = network.get_channel_database();
					ArrayList<classChannelHolder> channels = new ArrayList<classChannelHolder>();
					ArrayList<Integer> channel_numbers = new ArrayList<Integer>(channel_database.get_all_channels());
					ArrayList<classRecovery> recovery_table = new ArrayList<classRecovery>(channel_database.get_recovery_table());
					classChannelHolder channel_holder;
					for(int i = 0; i < channel_numbers.size();i++){
						channel_holder = new classChannelHolder(channel_numbers.get(i), 
								channel_database.get_channel_name(channel_numbers.get(i)), 
								channel_database.get_channel_paths(channel_numbers.get(i)),true);
						//What is the point of having a channel with no episodes?
						if (channel_holder.channel_size() > 0){
							channels.add(channel_holder);
							//
							if (i<recovery_table.size()){
								channels.get(recovery_table.get(i).channel_number).get_episode(recovery_table.get(i).channel_episode);
								channels.get(recovery_table.get(i).channel_number).set_episode_offset(recovery_table.get(i).episode_offset);
							}
						}
						int progress  = (int) (((i+1) / (float) channel_numbers.size()) * 100);
						Log.i("activityLoadingScreen","Progress: " + String.valueOf(progress) + "%");
						publishProgress(progress);
					}
					network.async_network_update(channels);
	            }
			}
			return null;
		}
		
		@Override
		protected void onProgressUpdate(Integer... progress) {
			network_status.setText("Loading: " + String.valueOf(progress[0]) + "%");
			//progressBar.setProgress(progress[0]);
	     }
		
		@Override
	    protected void onPostExecute(Void v) {
			verify_network.setVisibility(View.VISIBLE);
			network_status.setText("Network Status");
			if(!globals.get_network_loaded()){
				Log.i("ActivityCurrentChannel","Setting global");
				globals.set_network_object(network);
				globals.set_network_loaded(true);
			}else{
				network = globals.get_network_object();
			}
			
            if(!network.network_empty()){
				verify_network.setImageDrawable(getResources().getDrawable(R.drawable.object_circle_green));
			}
	    	set_things_up();
	    }
	}

	public void bind_billing_activities(){
		mServiceConn = new ServiceConnection() {
			   @Override
			   public void onServiceDisconnected(ComponentName name) {
				   logger.info("Billing Service Disconnected...");
				   mService = null;
			   }

			   @Override
			   public void onServiceConnected(ComponentName name, IBinder service) {
				   logger.info("Billing Service Connected...");
				   mService = IInAppBillingService.Stub.asInterface(service);
			   }
		};
		bindService(new Intent("com.android.vending.billing.InAppBillingService.BIND"), mServiceConn, Context.BIND_AUTO_CREATE);
	}
	
	public void sent_donation_purchase(){
		classDeveloperPayload payload = new classDeveloperPayload();
    	
    	LoadBillingTask task = new LoadBillingTask(payload.get_payload(), "mytv_donation");
    	
    	task.run();
	}
	
    class LoadBillingTask extends TimerTask {
        private Handler mHandler = new Handler(Looper.getMainLooper());
		String payload;
		String item_name;

        LoadBillingTask(String payload, String item_name){
        	logger.info("Init Billing");
  			this.payload = payload;
  			this.item_name = item_name;
  			logger.info("Done Init Billing");
        }
        
        @Override
        public void run() {
           mHandler.post(new Runnable() {
              public void run() {
            	  try {
            		  logger.info("Starting runnable");
            		  logger.info("package: " + getPackageName());
            		  logger.info("item: " + item_name);
            		  logger.info("payload: " + payload);
            		if(mService == null){
            			logger.info("mService: invalid");
            			logger.toast("There was a problem connecting to the billing service", self);
            		}else{
            			logger.info("mService: valid");
            			buyIntentBundle = mService.getBuyIntent(3, getPackageName(), item_name, "inapp", payload);
            			logger.info("Intent info");
            			if(buyIntentBundle.getInt("RESPONSE_CODE") != 7){
	            			logger.info("Starting pending intent");
	            			
	          				PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT");
	          				
	          				logger.info("Starting sender for result");
	          				startIntentSenderForResult(pendingIntent.getIntentSender(),
	          					   1641, new Intent(), Integer.valueOf(0), Integer.valueOf(0),
	          					   Integer.valueOf(0));
            			}else{
            				logger.toast("This product has already been purchased!", self);
            			}
            		}
      			} catch (RemoteException e) {
      				logger.error(e.toString());
      				e.printStackTrace();
      			} catch (SendIntentException e) {
      				logger.error(e.toString());
      				e.printStackTrace();
      			} catch (Exception e){
      				logger.error(e.toString());
      				e.printStackTrace();
      			}
              }
           });
         }
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)    
    {
        super.onActivityResult(requestCode, resultCode, data);
        logger.info("RequestCode: " + requestCode);
        logger.info("ResultCode: " + resultCode);
        if (requestCode == 1641 && resultCode == Activity.RESULT_OK) {           
        	logger.info("onactivity result called inside request code");
            try{
            	
            	logger.info("Parsing response data");
	            int responseCode = data.getIntExtra("RESPONSE_CODE", 0);
	            logger.info("ResponseCode: " + responseCode);
	            String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");
	            logger.info("purchaseData: " + purchaseData);
	            String dataSignature = data.getStringExtra("INAPP_DATA_SIGNATURE");
	            logger.info("dataSignature: " + dataSignature);
	            
	            
	            if (responseCode == Constants.BILLING_RESPONSE_RESULT_OK) {
	                try {
    	                JSONObject jo = new JSONObject(purchaseData);
    	                String sku = jo.getString("productId");
    	                logger.info("productId: " + sku);
    	                //This is where the purchase needs to actually be put into the system...
    	                
    	                JSONObject o = new JSONObject(purchaseData);
    	                logger.info("Purchase Data: " + o.toString());
    	                String mOrderId = o.optString("orderId");
    	                logger.info("mOrderId: " + mOrderId);
    	                String mPackageName = o.optString("packageName");
    	                logger.info("mPackageName: " + mPackageName);
    	                String mSku = o.optString("productId");
    	                logger.info("mSku: " + mSku);
    	                long mPurchaseTime = o.optLong("purchaseTime");
    	                logger.info("purchaseTime: " + mPurchaseTime);
    	                int mPurchaseState = o.optInt("purchaseState");
    	                logger.info("mPurchaseState: " + mPurchaseState);
    	                String mDeveloperPayload = o.optString("developerPayload");
    	                logger.info("mDeveloperPayload: " + mDeveloperPayload);
    	                String mToken = o.optString("token", o.optString("purchaseToken"));
    	                logger.info("mToken: " + mToken);
    	                
    	                //Need to consume the purchase before returning
    	                try {
    	                    mService.consumePurchase(3, getPackageName(), mToken);
    	                } catch (RemoteException e) {
    	                	logger.error(e.toString());
    	                    e.printStackTrace();
    	                }
    	                
    	                //This is the method that reflects back to the prototype
                		Object[] parameterTypes = new Object[2];
                        parameterTypes[0] = Integer.valueOf(o.optString("developerPayload").split(">>>")[0]);
                        parameterTypes[1] = mToken;
                		
    					try {
	    	                logger.toast("Thank you for your donation! Now we can afford to eat tonight!", self);
    						
    					} catch (IllegalArgumentException e) {
    						// TODO Auto-generated catch block
    						logger.error(e.toString());
    						e.printStackTrace();
    					} 
	                }catch (JSONException e) {
	                            Toast.makeText(this, "Failed to parse purchase data.", Toast.LENGTH_SHORT);
	                            logger.error(e.toString());
	                            e.printStackTrace();
	                }
	                }else if (responseCode == Constants.BILLING_RESPONSE_RESULT_USER_CANCELED) {
	                	logger.error("User cancelled purchase"); 
	                	Toast.makeText(this, "User cancelled purchase.", Toast.LENGTH_SHORT).show();
	                }else if (responseCode == Constants.BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE) {
	                	logger.error("Your Device doesn't support inapp billing"); 
	                	Toast.makeText(this, "Your Device doesn't support inapp billing.", Toast.LENGTH_SHORT).show();
	                }else if (responseCode == Constants.BILLING_RESPONSE_RESULT_ITEM_UNAVAILABLE) {
	                	logger.error("Item is not available for billing"); 
	                	Toast.makeText(this, "Item is not available for billing", Toast.LENGTH_SHORT).show();
	                }else if (responseCode == Constants.BILLING_RESPONSE_RESULT_DEVELOPER_ERROR) {
	                	logger.error("Can't purchase item due to some developer error"); 
	                	Toast.makeText(this, "Can't purchase item due to some developer error.", Toast.LENGTH_SHORT).show();
	                }else if (responseCode == Constants.BILLING_RESPONSE_RESULT_ERROR) {
	                	logger.error("Can't purchase item due to some error in response"); 
	                	Toast.makeText(this, "Can't purchase item due to some error in response.", Toast.LENGTH_SHORT).show();
	                }else if (responseCode == Constants.BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED) {
	                	logger.error("You already own this item"); 
	                	Toast.makeText(this, "You already own this item.", Toast.LENGTH_SHORT).show();
	                }else if (responseCode == Constants.BILLING_RESPONSE_RESULT_ITEM_NOT_OWNED) {
	                	logger.error("You don't own this item");
	                    Toast.makeText(this, "You don't own this item.", Toast.LENGTH_SHORT).show();
	                }
            }catch(Exception e){
            	logger.error(e.toString());
            	logger.error("Unable to make purchase");
            	Toast.makeText(this, "Unable to make purchase.", Toast.LENGTH_SHORT).show();
            }
        }
        
    }
    
    public class Constants{
    	static final int BILLING_RESPONSE_RESULT_OK	= 0;
    	static final int BILLING_RESPONSE_RESULT_USER_CANCELED = 1;
    	static final int BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE = 3;
    	static final int BILLING_RESPONSE_RESULT_ITEM_UNAVAILABLE	= 4;
    	static final int BILLING_RESPONSE_RESULT_DEVELOPER_ERROR = 5;
    	static final int BILLING_RESPONSE_RESULT_ERROR = 6;
    	static final int BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED = 7;
    	static final int BILLING_RESPONSE_RESULT_ITEM_NOT_OWNED = 8;
    }
	
}